<template>
  <div class="wrap">
    <el-form ref="form" :model="order" label-width="120px" class="odForm" :rules="rules">
      <el-form-item label="消费手机号" style="margin-top: 30px" prop="phone">
        <el-input @blur="checkIsMember" style="width: 300px" v-model="order.phone" maxlength="11" minlength="11"
                  placeholder="请输入11位手机号"></el-input>
      </el-form-item>
      <el-form-item label="预约时间段" prop="timeSelect">
        <el-select v-model="order.reservation" placeholder="请选择预约时间段">
          <el-option v-for="item in timeList"
                     :label="item.time" :value="item.time"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择场所" prop="area">
        <el-select v-model="order.area" placeholder="请选择场所">
          <el-option v-for="item in areaList"
                     :label="item.name+'-剩余容量:'+(item.limitNum-item.current)" :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消费金额(￥元)">
        <el-select v-model.number="initPrice" placeholder="请选择消费金额">
          <el-option :value="49.9"></el-option>
          <el-option :value="69.9"></el-option>
          <el-option :value="99.9"></el-option>
          <el-option :value="119.9"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消费人数">
        <el-input-number v-model="personNum" @change="handlePersonNumChange" :min="1"
                         label="进场人数"></el-input-number>
      </el-form-item>
      <el-form-item label="选择折扣">
        <el-select v-model="discount" placeholder="请选择折扣">
          <el-option label="不打折" :value="1.0"></el-option>
          <el-option label="95折" :value="0.95"></el-option>
          <el-option label="85折" :value="0.85"></el-option>
          <el-option label="7折" :value="0.7"></el-option>
          <el-option label="65折" :value="0.65"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否会员">
        <el-switch
            v-model="order.isMember===1"
            active-text="是"
            inactive-text="否"
            disabled>
        </el-switch>
      </el-form-item>
      <div class="price-box">
        <span style="color: #000000;font-size: 16px;font-weight: bold;margin-right: 6px">价格:</span>
        ￥{{ finalPrice }}
        <span class="original-price" v-show="this.originalPrice!=this.finalPrice">
                {{ originalPrice }}
                </span>
      </div>
      <el-form-item>
        <el-button style="margin-left: 60px" type="primary" @click="createOrder" plain>创建订单</el-button>
      </el-form-item>
    </el-form>
    <pay-page ref="pay" :orderMap="orderContent" @saveTheOrder="saveTheOrder"></pay-page>
  </div>
</template>

<script>
import {checkMemberAccount} from '@/utils/apis/member'
import {getAllArea} from '@/utils/apis/area'
import {getAllTime, saveNewOrder} from '@/utils/apis/order'
import PayPage from "@/views/PayPage";

export default {
  name: "NewOrder",
  components: {PayPage},
  data() {
    let checkPhone = (rule, value, callback) => {
      // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!this.isCellPhone(value)) {
        // 引入methods中封装的检查手机格式的方法
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      //区域列表
      areaList: [],
      order: {
        phone: '',
        isMember: 0,
        // area: this.areaList[0].name,
        area: '',
        price: this.finalPrice,
        reservation:''
      },
      discount: 1,
      initPrice: 49.9,
      personNum: 1,
      fullscreenLoading: false,
      updatePersonNum: 0,
      areaIndex: 0,
      orderContent: {
        type: 'area',
        price: 129,
        subject: 'vitality健身房入场消费'
      },
      rules: {
        phone: [{required: true, validator: checkPhone, trigger: 'blur'}],
        area: [{required: true, message: '请选择锻炼区域', trigger: 'blur'}],
      },
      timeList: []
    }
  },
  created() {
    this.getAllAreaInfo()
    this.getTimes()
  },
  computed: {
    //最终价格
    finalPrice() {
      let totalPrice = this.initPrice * this.personNum;
      //当是会员时
      if (this.order.isMember === 1) {
        //会员打九折
        totalPrice = 0.9 * totalPrice
      }
      let price = Math.round(totalPrice * this.discount * 100) / 100
      this.order.price = price
      return price
    },
    //原始价格
    originalPrice() {
      return Math.round(this.initPrice * this.personNum * 100) / 100
    }
  },
  methods: {
    getTimes() {
      getAllTime().then(res => {
        console.log(res)
        this.timeList = res.data.data
      })
    },
    async getAllAreaInfo() {
      await getAllArea().then(res => {
        const areas = res.data.data
        let arr = []
        areas.forEach(area => {
          if (area.limitNum - area.current > 0) {
            arr.push(area)
          }
        })
        this.areaList = arr
        this.area = this.areaList[0].name
      })
    },
    //判断是否为手机号
    isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    //判断手机号是否会员
    async checkIsMember() {
      if (this.order.phone !== '') {
        await checkMemberAccount(this.order.phone).then(res => {
          const flag = res.data.data
          if (flag) {
            this.order.isMember = 1
          } else {
            this.order.isMember = 0
          }
        })
      }
    },
    createOrder() {
      console.log(this.$store.state)
      if (this.order.isMember == 1 && this.personNum > 1) {
        this.personNum = 1
        this.$message.warning("会员仅可自己使用")
      }
      if (this.order.phone.length != 11 || this.order.area == '') {
        this.$message.warning("请完整且正确填写表单")
      } else {
        const loading = this.$loading({
          lock: true,
          text: '订单生成中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        //遍历缓存中的area,查找当前人数,获取修改数据
        const areas = this.areaList
        let i = areas.length
        while (i--) {
          if (areas[i].name === this.order.area) {
            this.updatePersonNum = areas[i].current + this.personNum
            this.areaIndex = i
          }
        }
        this.orderContent.price = this.order.price
        this.$refs.pay.toPayment()
        loading.close();
      }
    },
    saveTheOrder() {
      //订单生成请求
      saveNewOrder(this.order, this.updatePersonNum).then(res => {
        if (res.data.code === 200) {
          //更新当前地区信息缓存

          // this.$store.commit('updateAreaCurrentPerson', {
          //     areaIndex: this.areaIndex,
          //     change: this.updatePersonNum
          // })
          this.$message.success('订单提交成功')
          this.order = {
            phone: '',
            isMember: 0,
            area: '',
            price: 49.9
          }
          this.personNum = 1
          this.getAllAreaInfo()
        }
      })
    },
    //当消费人数改变时
    handlePersonNumChange(val) {
      if (this.order.area === '') {
        //当还未选择场所时
        this.$message.warning("请先选择运动场所")
        this.$nextTick(() => {
          this.personNum = 1
        });
      } else {
        //判断场所人数上限
        const areaName = this.order.area
        this.areaList.forEach(item => {
          if (item.name === areaName) {
            //当获取到所在场所数量上限   判断
            if (val > (item.limitNum - item.current)) {
              this.$nextTick(() => {
                this.personNum = item.limitNum - item.current
              });
            }
          }
        })
      }
    },
  }
}
</script>

<style scoped>
.wrap {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.odForm {
  width: 450px;
  height: 600px;
  margin-top: 50px;
  box-shadow: 1px 1px 6px rgba(30, 30, 30, .3);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.price-box {
  padding-left: 60px;
  padding-bottom: 40px;
  width: 250px;
  color: #e33636;
  font-size: 30px;
  font-weight: bold;
}

.original-price {
  color: rgba(121, 123, 127, 0.9);
  text-decoration: line-through;
  font-size: 19px;
}
</style>